<template>
  <div class="overview-page">
    <!-- 添加通用页头 -->
    <PageHeader title="我的概况" :showLeftButton="false" />
    <div class="content">
      <PullRefresh @refresh="onRefresh">
      
      <template v-if="loading">
        <!-- 加载状态骨架屏 -->
        <div class="stats-grid">
          <el-card class="stat-card" v-for="i in 4" :key="`stat-${i}`">
            <div class="stat-content">
              <el-skeleton animated style="width: 60px; height: 36px;"></el-skeleton>
              <el-skeleton animated style="width: 80px; height: 20px; margin-top: 8px;"></el-skeleton>
            </div>
          </el-card>
        </div>
        
        <el-card style="margin: 1rem;">
          <template #header>
            <div class="card-header">
              <el-skeleton animated style="width: 80px; height: 20px;"></el-skeleton>
              <el-skeleton animated style="width: 80px; height: 28px;"></el-skeleton>
            </div>
          </template>
          <div class="recent-events">
            <div class="event-item" v-for="i in 3" :key="`event-${i}`">
              <el-skeleton animated style="width: 100px; height: 16px;"></el-skeleton>
              <div class="event-info">
                <el-skeleton animated style="width: 200px; height: 20px; margin-bottom: 8px;"></el-skeleton>
                <el-skeleton animated style="width: 300px; height: 16px;"></el-skeleton>
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card style="margin: 1rem;">
          <template #header>
            <div class="card-header">
              <el-skeleton animated style="width: 120px; height: 20px;"></el-skeleton>
            </div>
          </template>
          <div class="type-stats">
            <div class="type-stat-item" v-for="i in 4" :key="`type-${i}`">
              <div class="type-info">
                <el-skeleton animated style="width: 30px; height: 30px;"></el-skeleton>
                <el-skeleton animated style="width: 80px; height: 16px; margin-left: 10px;"></el-skeleton>
              </div>
              <div class="type-progress">
                <el-skeleton animated style="width: 100%; height: 8px; margin-top: 8px;"></el-skeleton>
              </div>
            </div>
          </div>
        </el-card>
      </template>
      
      <template v-else>
        <div class="stats-grid">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ totalEvents }}</div>
              <div class="stat-label">总事件数</div>
            </div>
          </el-card>
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ recentEventsCount }}</div>
              <div class="stat-label">近期事件</div>
            </div>
          </el-card>
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ eventTypesCount }}</div>
              <div class="stat-label">事件类型</div>
            </div>
          </el-card>
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ daysSinceFirst }}</div>
              <div class="stat-label">记录天数</div>
            </div>
          </el-card>
        </div>
        
        <el-card style="margin: 1rem;">
          <template #header>
            <div class="card-header">
              <span>近期事件</span>
              <el-button type="text" @click="viewAll">查看全部</el-button>
            </div>
          </template>
          <div class="recent-events">
            <div 
              v-for="event in recentEvents" 
              :key="event.id" 
              class="event-item"
              @click="viewDetail(event.id)"
            >
              <div class="event-date">{{ formatDate(event.date) }}</div>
              <div class="event-info">
                <h4>{{ event.title || '未命名事件' }}</h4>
                <p>{{ event.description || '暂无描述' }}</p>
              </div>
            </div>
            <div v-if="recentEvents.length === 0" class="no-data">
              <p>暂无事件记录</p>
            </div>
          </div>
        </el-card>
        
        <el-card style="margin: 1rem;">
          <template #header>
            <div class="card-header">
              <span>事件类型统计</span>
            </div>
          </template>
          <div class="type-stats">
            <div 
              v-for="type in typeStats" 
              :key="type.value"
              class="type-stat-item"
            >
              <div class="type-info">
                <span class="type-icon">{{ type.icon }}</span>
                <span class="type-name">{{ type.label }}</span>
              </div>
              <div class="type-progress">
                <el-progress 
                  :percentage="type.percentage" 
                  :color="type.color"
                  :stroke-width="8"
                ></el-progress>
                <span class="type-count">{{ type.count }}</span>
              </div>
            </div>
            <div v-if="typeStats.length === 0" class="no-data">
              <p>暂无事件类型统计数据</p>
            </div>
          </div>
        </el-card>
      </template>
      </PullRefresh>
    </div>
  </div>
</template>

<script>
import PageHeader from '../components/PageHeader.vue'
import PullRefresh from '../components/PullRefresh.vue'
import { getAllEvents } from '../services/api.js'
export default {
  name: 'OverviewPage',
  components: {
    PageHeader,
    PullRefresh
  },
  data() {
    return {
      events: [],
      loading: false,
      totalEvents: 0,
      recentEventsCount: 0,
      eventTypesCount: 0,
      daysSinceFirst: 0,
      recentEvents: [],
      typeStats: [],
      eventTypes: {
        education: { label: '教育经历', icon: '🎓', color: '#409eff' },
        career: { label: '职业发展', icon: '💼', color: '#67c23a' },
        family: { label: '家庭生活', icon: '👪', color: '#e6a23c' },
        health: { label: '健康状况', icon: '🏥', color: '#f56c6c' },
        travel: { label: '旅行经历', icon: '✈️', color: '#909399' },
        hobby: { label: '兴趣爱好', icon: '🎨', color: '#c06c84' },
        social: { label: '社交活动', icon: '👥', color: '#5f76e8' },
        other: { label: '其他事件', icon: '📋', color: '#909399' }
      }
    }
  },
  mounted() {
    // 组件挂载时获取事件数据
    this.fetchEvents()
  },
  methods: {
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric' 
      })
    },
    viewDetail(id) {
      this.$router.push(`/event-detail/${id}`)
    },
    viewAll() {
      this.$router.push('/event-manage')
    },
    
    // 从后端获取事件数据
    async fetchEvents() {
      try {
        this.loading = true
        // 调用API获取所有事件
        const eventData = await getAllEvents()
        
        if (Array.isArray(eventData)) {
          // 处理返回的数据，确保字段映射正确
          this.events = eventData.map(event => ({
            ...event,
            type: event.event_type || event.type
          }))
          
          // 计算统计数据
          this.calculateStats()
          console.log('成功获取事件数据并计算统计信息')
        }
      } catch (error) {
        console.error('获取事件数据失败:', error)
        this.$message.error('获取数据失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    // 计算统计数据
    calculateStats() {
      // 总事件数
      this.totalEvents = this.events.length
      
      // 近期事件（按照日期降序排列，取前5个）
      this.recentEvents = [...this.events]
        .filter(event => event.date) // 确保有日期
        .sort((a, b) => new Date(b.date) - new Date(a.date))
        .slice(0, 5)
      this.recentEventsCount = this.recentEvents.length
      
      // 事件类型统计
      const typeCounts = {}
      this.events.forEach(event => {
        const type = event.type
        typeCounts[type] = (typeCounts[type] || 0) + 1
      })
      
      // 构建类型统计数据
      this.typeStats = Object.keys(typeCounts)
        .map(type => {
          const typeInfo = this.eventTypes[type] || { label: '未知类型', icon: '📋', color: '#909399' }
          const percentage = this.totalEvents > 0 ? Math.round((typeCounts[type] / this.totalEvents) * 100) : 0
          return {
            label: typeInfo.label,
            value: type,
            icon: typeInfo.icon,
            count: typeCounts[type],
            percentage: percentage,
            color: typeInfo.color
          }
        })
        .sort((a, b) => b.count - a.count) // 按数量降序排列
      
      this.eventTypesCount = Object.keys(typeCounts).length
      
      // 计算记录天数
      if (this.events.length > 0) {
        const dates = this.events
          .filter(event => event.date) // 确保有日期
          .map(event => new Date(event.date))
        const minDate = new Date(Math.min(...dates))
        const maxDate = new Date(Math.max(...dates))
        this.daysSinceFirst = Math.round((maxDate - minDate) / (1000 * 60 * 60 * 24)) + 1
      } else {
        this.daysSinceFirst = 0
      }
    },
    
    // 下拉刷新回调
    async onRefresh() {
      try {
        await this.fetchEvents()
        this.$message.success('数据已刷新')
      } catch (error) {
        console.error('刷新数据失败:', error)
        this.$message.error('刷新失败，请重试')
      }
    }
  }
}
</script>

<style scoped>
.overview-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  width: 100%;
  padding-bottom: 60px;
}

.content {
  width: 100%;
  margin: 0;
  height: calc(100vh - 60px); /* 假设页头高度为60px */
  overflow: hidden;
}

.content h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  padding: 1rem;
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 2.5rem;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 0.5rem;
}

.stat-label {
  font-size: 1.1rem;
  color: #666;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.recent-events {
  max-height: 300px;
  overflow-y: auto;
  margin-top: 8px;
}

.event-item {
  display: flex;
  padding: 1rem 0;
  border-bottom: 1px solid #e0e0e0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.event-item:last-child {
  border-bottom: none;
}

.event-item:hover {
  background-color: #f5f5f5;
}

.event-date {
  width: 120px;
  color: #666;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.event-info {
  flex: 1;
}

.event-info h4 {
  margin: 0 0 0.5rem 0;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.event-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.type-stats {
  padding: 1rem 0;
  margin-top: 16px;
}

.type-stat-item {
  margin-bottom: 1.5rem;
}

.type-stat-item:last-child {
  margin-bottom: 0;
}

.type-info {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.type-icon {
  font-size: 1.5rem;
  margin-right: 0.5rem;
}

.type-name {
  font-size: 1rem;
  color: #333;
  font-weight: 500;
}

.type-progress {
  position: relative;
  padding-right: 40px;
}

.type-count {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
  font-size: 0.9rem;
}

/* 加载状态样式 */
.loading-state .el-skeleton {
  margin-bottom: 8px;
}

.loading-state .type-progress .el-skeleton {
  border-radius: 4px;
}

.loading-state .stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-state .event-item {
  opacity: 0.7;
  cursor: default;
}

.loading-state .event-item:hover {
  background-color: transparent;
}

.loading-state .type-info {
  justify-content: flex-start;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .event-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 16px 0;
  }
  
  .event-date {
    width: auto;
    text-align: left;
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .type-progress {
    padding-right: 30px;
  }
  
  /* 移动端加载状态优化 */
  .loading-state .event-info .el-skeleton {
    width: 100% !important;
    max-width: 250px;
  }
}

/* 动画优化 */
.stat-card,
.event-item,
.type-stat-item {
  transition: all 0.3s ease;
}

/* 优化空状态显示 */
.no-data {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.no-data p {
  margin: 0;
  font-size: 16px;
}
</style>